#coding=utf-8
__author__ = 'Administrator'
from web.models import *
import time
# import the logging library
import logging
logger = logging.getLogger('django')


def get_info(book_id):
    book = Book.objects.get(book_id=book_id)

    pages = Page.objects(book_id=book_id).order_by('page_id')

    return book, pages


def take_log():
    k = 100
    data = []
    while True:
        try:
            loginfo = log.pop(0)
            data.append(loginfo)
        except Exception as e:
            loginfo = unicode(e)
            #logger.debug(loginfo)
            #time.sleep(0.5)
            if k == 0:
                loginfo = None
                break
            k -= 1

    return data


def check(start_book_id, end_book_id):

    books = Book.objects(Q(book_id__gte=start_book_id) & Q(book_id__lte=end_book_id))
    pers = []
    for book in books:
        try:
            per = int(round(1. * int(book.chapters_had)/int(book.chapters_should_have) * 100))
        except Exception:
            per = 0

        pers.append([book.book_name, per])
    pers.sort(key=lambda p: p[1], reverse=True)
    return pers


def get_page(book_id, page_id):
    page = Page.objects.get(book_id=book_id, page_id=page_id)
    return page